package com.computercourse.order.service;

import com.computercourse.framework.domain.task.CicTask;
import com.computercourse.framework.domain.task.CicTaskHis;
import com.computercourse.order.dao.CicTaskHisRepository;
import com.computercourse.order.dao.CicTaskRepository;
import com.github.pagehelper.Page;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TaskService {

    @Autowired
    private CicTaskRepository cicTaskRepository;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private CicTaskHisRepository cicTaskHisRepository;

    //取出前n条任务,取出指定时间之前处理的任务
      public List<CicTask> findTaskList(Date updateTime, int n){

          //设置分页参数，取出前n 条记录
          Pageable pageable = new PageRequest(0, n);
          Page<CicTask> cicTasks = cicTaskRepository.findByUpdateTimeBefore(pageable,updateTime);
          return cicTasks.getResult();
      }


    /*** //发送消息 * @param xcTask 任务对象 * @param ex 交换机id * @param routingKey */
    @Transactional
    public void publish(CicTask cicTask, String ex, String routingKey){

        //查询任务
        Optional<CicTask> taskOptional = cicTaskRepository.findById(cicTask.getId());

        if(taskOptional.isPresent()){

            CicTask cicTask1 = taskOptional.get();
            //String exchange, String routingKey, Object object
            rabbitTemplate.convertAndSend(ex,routingKey,cicTask1);
            //更新任务时间为当前时间
            cicTask1.setUpdateTime(new Date());
            cicTaskRepository.save(cicTask1);
        }

    }


    @Transactional
    public int getTask(String taskId,int version){
        //通过乐观锁的方式来更新数据表
        return cicTaskRepository.updateTaskVersion(taskId, version);
    }

    //删除任务
    @Transactional
    public void finishTask(String taskId){

        Optional<CicTask> taskOptional = cicTaskRepository.findById(taskId);

        if(taskOptional.isPresent()){

            CicTask cicTask = taskOptional.get();
            cicTask.setDeleteTime(new Date());
            CicTaskHis xcTaskHis = new CicTaskHis();
            BeanUtils.copyProperties(cicTask, xcTaskHis);
            cicTaskHisRepository.save(xcTaskHis);
            cicTaskRepository.delete(cicTask);

        }
    }
}

